/**
 * 招聘需求，需求认领页
 *  refuseStatus 需求接受状态（0 待接受 1 接受 2拒绝）
 */
import React from 'react';
import { Row, Button, Card, Divider, Tag, message, Modal, Icon, Form, Input, Alert } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import pageTabUtil from '@/utils/pageTabUtil';
import { useRequest, defaultFormatResult } from '@/hooks';
import { Descriptions } from '@/molecules';
import { connect } from 'umi';
import { getDemand, recruitClaim } from '../service';
import { DemandAccept } from '../containers';

const DemandDetail = ({ data = {} }) => {
    const {
        organizationName = '--',
        workCity = '--',
        recruitNums = '0',
        workNatureName = '--',
        entryDateStart = '--',
        entryDateEnd = '--',
        recruitDegreeName = '--',
        workYearsName = '--',
        dutyName = '--',
        rankValue = '--',
        positionDesc = '',
        jobRequirement = '',
        positionTag = '',
        positionName = ''
    } = data;

    const time = entryDateStart && entryDateEnd ? `${entryDateStart}~${entryDateEnd}` : '--';

    const descriptions1 = [
        { label: '岗位名称', value: dutyName },
        { label: '需求部门', value: organizationName },
        { label: '工作城市', value: workCity },
        { label: '需求人数', value: recruitNums },
        { label: '工作性质', value: workNatureName },
        { label: '到岗时间', value: time }
    ];

    const descriptions2 = [
        { label: '经验和学历', value: `${workYearsName}/${recruitDegreeName}` },
        { label: '匹配职位', value: `${positionName}/${rankValue}` },
        {
            label: '职位要求',
            value: `${positionDesc}`
        },
        {
            label: '岗位要求',
            value: jobRequirement
        },
        {
            label: '职位关键词',
            value: positionTag.split(',').map(item => (item ? <Tag key={item}>{item}</Tag> : null))
        }
    ];

    return (
        <Row type="flex">
            <Descriptions title="基本信息" descriptions={descriptions1} />
            <Divider />
            <Descriptions title="岗位要求" descriptions={descriptions2} />
        </Row>
    );
};

const Claim = ({ location, form, user = {} }) => {
    const { currentUser } = user;
    const { query } = location;
    const { id } = query;
    const [submitLoading, setSubmitLoading] = React.useState(false);
    const [visible, setVisible] = React.useState(false);
    const { data, loading } = useRequest(() => getDemand(id), { ...defaultFormatResult });

    // 1接受 2拒绝
    const claim = params => {
        setSubmitLoading(true);
        recruitClaim({
            id,
            ...params
        })
            .then(res => {
                const { code, msg } = res;
                if (code === 10000) {
                    setVisible(false);
                    message.success('操作成功');
                    pageTabUtil.goBack();
                } else {
                    message.error(msg);
                }
            })
            .finally(() => {
                setSubmitLoading(false);
            });
    };

    const handleRefuse = () => {
        form.validateFields(async (err, values) => {
            if (!err) {
                claim({
                    operateType: 2,
                    ...values
                });
            }
        });
    };

    React.useEffect(() => {
        if (!visible) {
            form.resetFields();
        }
    }, [visible]);

    // 是否为当前招聘负责人
    const isCurrentPrincipal = currentUser.employeeCode === data?.preparePrincipalEmployeeCode;

    const renderExtra = () => {
        if (data?.refuseStatus === 2) {
            return (
                <DemandAccept
                    antButton
                    data={data}
                    onSuccess={() => {
                        pageTabUtil.goBack();
                    }}
                />
            );
        }
        if (loading || !isCurrentPrincipal) {
            return null;
        }
        return (
            <>
                <Button style={{ marginRight: 8 }} disabled={submitLoading} onClick={() => setVisible(true)}>
                    拒绝
                </Button>
                <Button type="primary" loading={submitLoading} onClick={() => claim({ operateType: 1 })}>
                    接受
                </Button>
            </>
        );
    };

    const renderMessage = () => {
        if (data?.refuseStatus === 2) {
            return null;
        }
        if (data?.refuseStatus === 1) {
            return `该需求已被 ${data?.principalEmployeeName} 认领`;
        }
        if (!isCurrentPrincipal) {
            return `${data?.updatePricipalEmployeeName} 已修改招聘负责人为 ${data?.preparePrincipalEmployeeName}，待 ${data?.preparePrincipalEmployeeName} 认领`;
        }
        return null;
    };

    return (
        <PageHeaderWrapper>
            <Card title="需求认领" bordered={false} loading={loading} extra={renderExtra()}>
                {renderMessage() && <Alert message={renderMessage()} type="warning" style={{ marginBottom: 16 }} />}
                <DemandDetail data={data} />
            </Card>
            <Modal
                title="拒绝招聘需求"
                width={700}
                visible={visible}
                onOk={handleRefuse}
                onCancel={() => setVisible(false)}
                okText="确认"
                okButtonProps={{ loading: submitLoading }}
                cancelText="取消"
            >
                <div style={{ padding: '20px 50px', fontSize: 18, color: '#000' }}>
                    <Icon type="warning" theme="filled" style={{ fontSize: 24, color: '#faad14', marginRight: 12 }} />
                    确认要拒绝此招聘任务？
                </div>
                <Form labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
                    <Form.Item label="拒绝理由">
                        {form.getFieldDecorator('refuseReason', {
                            rules: [
                                {
                                    required: true,
                                    message: '拒绝理由不能为空',
                                    whitespace: true
                                }
                            ]
                        })(
                            <Input.TextArea
                                placeholder="请输入拒绝理由"
                                autosize={{ minRows: 3, maxRows: 6 }}
                                maxLength={100}
                            />
                        )}
                    </Form.Item>
                </Form>
            </Modal>
        </PageHeaderWrapper>
    );
};

export default connect(({ user }) => ({ user }))(Form.create({})(Claim));
